package com.weikuang.fareast.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.trello.rxlifecycle2.android.ActivityEvent;
import com.weikuang.fareast.R;
import com.weikuang.fareast.adapter.ChangeAdapter;
import com.weikuang.fareast.bean.AddListEvent;
import com.weikuang.fareast.bean.ChangeBean;
import com.weikuang.fareast.bean.Count1Bean;
import com.weikuang.fareast.bean.CountDetailBean;
import com.weikuang.fareast.bean.HotelBean;
import com.weikuang.fareast.bean.OfficeBean;
import com.weikuang.fareast.bean.SimpleBean;
import com.weikuang.fareast.bean.TeamBean;
import com.weikuang.fareast.bean.UsualGoodsBean;
import com.weikuang.fareast.http.MainHttp;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.dlc.commonlibrary.okgo.rx.OkObserver;
import cn.dlc.commonlibrary.ui.widget.CommonItemView;
import cn.dlc.commonlibrary.ui.widget.TitleBar;
import cn.dlc.commonlibrary.ui.widget.popup.CommonPopupList;
import cn.dlc.commonlibrary.utils.ToastUtil;
import cn.dlc.commonlibrary.utils.rv_tool.RecyclerViewUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

//修改订单

public class AddChangActivity extends BaseActivity {

    ChangeAdapter mStatisticsAdapter;
    @BindView(R.id.tv_hospital)
    TextView tvHospital;
    @BindView(R.id.drop_hospital)
    FrameLayout dropHospital;
    @BindView(R.id.item_hospital)
    CommonItemView itemHospital;
    @BindView(R.id.tv_offic)
    TextView tvOffic;
    @BindView(R.id.drop_offic)
    FrameLayout dropOffic;
    @BindView(R.id.item_offic)
    CommonItemView itemOffic;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.btn_read)
    Button btnRead;
    @BindView(R.id.mTitleBar)
    TitleBar mTitleBar;
    @BindView(R.id.tv_not)
    TextView tvNot;
    @BindView(R.id.drop_not)
    FrameLayout dropNot;
    @BindView(R.id.item_not)
    CommonItemView itemNot;
    @BindView(R.id.ed_not)
    EditText edNot;
    @BindView(R.id.btn_add)
    Button btnAdd;
    @BindView(R.id.tv_group)
    TextView tvGroup;
    @BindView(R.id.drop_group)
    FrameLayout dropGroup;
    @BindView(R.id.item_group)
    CommonItemView itemGroup;
    @BindView(R.id.btn_delete)
    Button btnDelete;


    private CommonPopupList mHospitalPopup, mOfficPopup, mNotPopup, mGropPopup;
    private List<HotelBean.DataBean> mHospitalList;
    private List<OfficeBean.DataBean> mOfficList;
    private List<TeamBean.DataBean> mTeamList;
    private List<UsualGoodsBean.DataBean> mNotList;
    String offic_id = "",hotel_id = "";
    int not_id = -1;
    List<ChangeBean> datasList = new ArrayList<>();
    String order_id = "";

    Count1Bean.DataBean data;

    private CountDetailBean mCountDetailBean;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_change_data;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_data);
        ButterKnife.bind(this);

        initView();
        InitRecyclerView();
        data = (Count1Bean.DataBean)getIntent().getSerializableExtra("data");
        if (data != null){
            tvHospital.setText(data.hotel);
            tvOffic.setText(data.office);
            offic_id = data.office_id;
            hotel_id = data.hotel_id;
            order_id = data.id;
            countDetail(data.id);
            getTeam(hotel_id);
        }

    }

    private void initView() {
        mHospitalPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropHospital)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvHospital.setText(item);

                        if (mHospitalList != null) {
                           // getOffice(mHospitalList.get(position).id);
                            hotel_id = mHospitalList.get(position).id;
                            getTeam(mHospitalList.get(position).id);
                        }

                    }
                })
                .build();
        mOfficPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropOffic)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvOffic.setText(item);
                        if (mOfficList != null) {
                            offic_id = mOfficList.get(position).id;
                            usualGoods(offic_id);
                            //selectGoods(offic_id);
                        }

                    }
                })
                .build();
        mGropPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropGroup)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvGroup.setText(item);
                        if (mTeamList != null) {
                            getOffice(mTeamList.get(position).id);
                           // usualGoods(offic_id);
//                            selectGoods(offic_id);
                        }

                    }
                })
                .build();
        mNotPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropNot)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvNot.setText(item);
                        if (mNotList != null) {
                            not_id = position;
                        }
                    }
                })
                .build();
    }

    private void InitRecyclerView() {
        mStatisticsAdapter = new ChangeAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mStatisticsAdapter);


        mStatisticsAdapter.setOnItemClickListener(new ChangeAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, ChangeBean data, int position) {
                datasList.remove(position);
                mStatisticsAdapter.setNewData(datasList);
            }
        });
    }

    @OnClick({R.id.drop_hospital, R.id.drop_offic, R.id.btn_read, R.id.drop_not, R.id.btn_add, R.id.btn_delete, R.id.drop_group})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.drop_hospital:
               // mHospitalPopup.showAsDropDown(view);
                tvHospital.setText("");
                hotel_id = "";
                startActivityForResult(new Intent(getActivity(),HotelActivity.class),2001);
                break;
            case R.id.drop_offic:
                mOfficPopup.showAsDropDown(view);
                break;
            case R.id.btn_read:
                countEdit();
                break;
            case R.id.drop_group:
                mGropPopup.showAsDropDown(view);
                break;
            case R.id.drop_not:
                mNotPopup.showAsDropDown(view);
                break;
            case R.id.btn_add:
                if (mNotList != null && mNotList.size() > 0) {
                    if (!isAdd(mNotList.get(not_id).id)) {
                        addData();
                    }
                } else {
                    ToastUtil.show(this, "没有可选数据");
                }
                break;
            case R.id.btn_delete:
                deleteData();
               // startActivity(StatisticsNoDataActivity.class);
                break;
        }
    }

    private boolean isAdd(String id) {
        Iterator<ChangeBean> it = datasList.iterator();
        while (it.hasNext()) {
            ChangeBean str = it.next();
            if (str.id.equals(id)) {
                ToastUtil.show(this, "已经存在");
                return true;
            }
        }
        return false;
    }

    private void addData() {
        if (!TextUtils.isEmpty(edNot.getText().toString())&&Integer.parseInt(edNot.getText().toString()) > 0) {
            if (not_id >= 0) {
                ChangeBean statisticsBean = new ChangeBean(mNotList.get(not_id).title, mNotList.get(not_id).spec, Integer.parseInt(edNot.getText().toString()), Integer.parseInt(edNot.getText().toString()),0,0, mNotList.get(not_id).id);
                datasList.add(statisticsBean);
            }
            mStatisticsAdapter.setNewData(datasList);
            ToastUtil.show(this, "添加成功");
        } else {
            ToastUtil.show(this, "数量要大于0");
        }
    }

    private void deleteData() {
        Iterator<ChangeBean> it = datasList.iterator();
        while (it.hasNext()) {
            ChangeBean str = it.next();

            if (str.num == 0&&str.backs == 0&&str.num_loss==0) {
                it.remove();
            }
        }
        mStatisticsAdapter.setNewData(datasList);
    }


    private void getOffice(String team_id) {
        if (TextUtils.isEmpty(hotel_id)){
            ToastUtil.show(getActivity(),"请选择医院");
            return;
        }
        MainHttp.get().getOffice(hotel_id,team_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<OfficeBean>() {
                    @Override
                    public void onSuccess(OfficeBean officeBean) {
                        List<String> datas = new ArrayList<>();
                        mOfficList = officeBean.data;
                        for (OfficeBean.DataBean bean : officeBean.data) {
                            datas.add(bean.title);
                        }
                        mOfficPopup.setData(datas);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }

    private void getTeam(String hotel_id) {

        MainHttp.get().getTeam(hotel_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<TeamBean>() {
                    @Override
                    public void onSuccess(TeamBean officeBean) {
                        List<String> datas = new ArrayList<>();
                        mTeamList = officeBean.data;
                        for (TeamBean.DataBean bean : officeBean.data) {
                            datas.add(bean.title);
                        }
                        mGropPopup.setData(datas);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }

    private void usualGoods(String offic_id) {
        datasList.clear();
        mStatisticsAdapter.setNewData(datasList);
        MainHttp.get().usualGoods(offic_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<UsualGoodsBean>() {
                    @Override
                    public void onSuccess(UsualGoodsBean officeBean) {

                        int num ,num_loss,backs;
                        for (UsualGoodsBean.DataBean bean : officeBean.data) {
                            num = 0;num_loss = 0;backs = 0;

                       //     if (offic_id .equals( data.office_id)) {
                                if (mCountDetailBean != null && mCountDetailBean.data != null) {
                                    for (CountDetailBean.DataBean bean1 : mCountDetailBean.data) {
                                        if (bean1.title.equals(bean.title)) {
                                            num = Integer.valueOf(bean1.amount);
                                            num_loss = Integer.valueOf(bean1.bad);
                                            backs = Integer.valueOf(bean1.back);
                                        }
                                    }
                                }
                           // }
                            ChangeBean statisticsBean = new ChangeBean(bean.title, bean.spec, num,num, num_loss,backs,bean.id);
                            datasList.add(statisticsBean);
                        }
                       // mStatisticsAdapter.setNewData(datasList);

                        if (officeBean.data != null && officeBean.data.size() > 0) {
                            ToastUtil.show(getActivity(), officeBean.msg);
                        } else {
                            ToastUtil.show(getActivity(), "数据为空");
                        }
                        selectGoods(offic_id);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                        selectGoods(offic_id);
                    }
                });
    }

    private void selectGoods(String offic_id) {
        MainHttp.get().selectGoods(offic_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<UsualGoodsBean>() {
                    @Override
                    public void onSuccess(UsualGoodsBean officeBean) {
                        List<String> datas = new ArrayList<>();
                        mNotList = officeBean.data;
                        for (UsualGoodsBean.DataBean bean : officeBean.data) {
                            datas.add(bean.title);
                        }
                        mNotPopup.setData(datas);

                        int num ,num_loss,backs;
                        for (UsualGoodsBean.DataBean bean : officeBean.data) {
                            num = 0;num_loss = 0;backs = 0;

                           // if (offic_id .equals( data.office_id)) {
                                if (mCountDetailBean != null && mCountDetailBean.data != null) {
                                    for (CountDetailBean.DataBean bean1 : mCountDetailBean.data) {
                                        if (bean1.title.equals(bean.title)) {
                                            num = Integer.valueOf(bean1.amount);
                                            num_loss = Integer.valueOf(bean1.bad);
                                            backs = Integer.valueOf(bean1.back);
                                        }
                                    }
                                }
                           // }

                            ChangeBean statisticsBean = new ChangeBean(bean.title, bean.spec, num, num, num_loss, backs, bean.id);
                            datasList.add(statisticsBean);

                        }
//                        List<ChangeBean> tempList= new ArrayList<ChangeBean>();
//                        for (int i = 0; i < datasList.size(); i++) {
//                            if (!tempList.contains(datasList.get(i))) {
//                                tempList.add(datasList.get(i));
//                            }
//                        }
                        datasList = removeDupliById(datasList);
                        mStatisticsAdapter.setNewData(datasList);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }
    public static List<ChangeBean> removeDupliById(List<ChangeBean> persons) {
        Set<ChangeBean> personSet = new TreeSet<>((o1, o2) -> o1.getId().compareTo(o2.getId()));
        personSet.addAll(persons);
        return new ArrayList<>(personSet);
    }
    private void countDetail(String orderId) {
        MainHttp.get().countDetail(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<CountDetailBean>() {
                    @Override
                    public void onSuccess(CountDetailBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        mCountDetailBean = hotelBean;
                        usualGoods(offic_id);

                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }

    private void countEdit() {
        if (TextUtils.isEmpty(hotel_id)) {
            ToastUtil.show(getActivity(), "请选择医院");
            return;
        }
        if (TextUtils.isEmpty(offic_id)) {
            ToastUtil.show(getActivity(), "请选择科室");
            return;
        }
        String goods_id = "", nums = "", bads = "",backs = "";
        clearNums();
        for (int i = 0; i < datasList.size(); i++) {
            goods_id = goods_id + datasList.get(i).id + ",";
        }
        if (!TextUtils.isEmpty(goods_id)) {
            goods_id = goods_id.substring(0, goods_id.length() - 1);
        } else {
            goods_id = "";
        }

        for (int i = 0; i < datasList.size(); i++) {
            nums = nums + datasList.get(i).num + ",";
            bads = bads + datasList.get(i).num_loss + ",";
            backs = backs + datasList.get(i).backs + ",";
        }
        if (!TextUtils.isEmpty(nums)) {
            nums = nums.substring(0, nums.length() - 1);
        } else {
            nums = "";
        }
        if (!TextUtils.isEmpty(bads)) {
            bads = bads.substring(0, bads.length() - 1);
            backs = backs.substring(0, backs.length() - 1);
        } else {
            bads = "";
            backs= "";
        }

        showWaitingDialog("请等待", true);
        MainHttp.get().countEdit(order_id, goods_id, nums, bads,backs,hotel_id,offic_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<SimpleBean>() {
                    @Override
                    public void onSuccess(SimpleBean bean) {
                        ToastUtil.show(AddChangActivity.this, bean.msg);
                        dismissWaitingDialog();
                        finishActivity();
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(AddChangActivity.this, message);
                        dismissWaitingDialog();
                    }
                });
    }

    /**
     * 是否清空为0数据
     * @return
     */
    private void clearNums(){
        Iterator<ChangeBean> ite = datasList.iterator();
        while(ite.hasNext()){
            ChangeBean str = (ChangeBean)ite.next();
            if(str.num == 0){
                ite.remove();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 4 && data != null) {
            HotelBean.DataBean mUserdata = (HotelBean.DataBean) data.getSerializableExtra("data");
            if (mUserdata != null) {
                tvHospital.setText(mUserdata.title);
                hotel_id = mUserdata.id;
                getTeam(hotel_id);
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new AddListEvent());
    }

}
